<template>
    <div id="container"></div>
</template>

<script>
import * as THREE from "three";
import { OBJLoader, MTLLoader } from "three-obj-mtl-loader";
import { OrbitControls } from "../common/tool/OrbitControls";
// import { GLTFLoader } from "../common/tool/GLTFLoader";
// import { DRACOLoader } from "../common/tool/DRACOLoader";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";

// var onProgress = function(xhr) {
//     if (xhr.lengthComputable) {
//         var percentComplete = xhr.loaded / xhr.total * 100;
//         console.log(Math.round(percentComplete, 2) + '% downloaded');
//     }
// };
export default {
  data() {
    return {
     publicPath: process.env.BASE_URL,
      /**场景 */
      scene: null,
      /**相机 */
      camera: null,
      /**渲染 */
      renderer: null,
      /**控制器 */
      controls: null,
      /**屋顶 */
      roof: null, 
      requestId: null,
      /**容器 */
      container: null
    };
  },
  methods: {
    /**初始化 */
    initScene() {
        this.scene = new THREE.Scene();
        // 环境光：
        const ambientLight = new THREE.AmbientLight(0xcccccc, 0.4);
        this.scene.add(ambientLight);
        // 辅助坐标系：
        var axisHelper = new THREE.AxisHelper(15);
        this.scene.add(axisHelper);
        //网格辅助线：
        var helper = new THREE.GridHelper(1080, 800, 0xCD3700, 0x4A4A4A);
        this.scene.add(helper);
    },
    initCamera() {
        const aspect = window.innerWidth / 1080; //宽高可根据实际项目要求更改 如果是窗口高度改为innerHeight
        // 透视投影相机：
        // this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
        // this.camera.position.set(0, 400, 600);
        // this.camera.lookAt(new THREE.Vector3(0, 0, 0));
        this.camera = new THREE.PerspectiveCamera(45, aspect, 1, 2000);
        this.camera.position.set(0, 20, 30);
        this.camera.lookAt(new THREE.Vector3(0, 0, 0)); // 让相机指向原点
        // // 点光源：
        const pointLight = new THREE.PointLight(0xffffff, 0.8);
        this.camera.add(pointLight);
        // var light = new THREE.SpotLight(0xffffff);
        // light.position.set(-300, 600, -400);
        // light.castShadow = true;
        // this.scene.add(light);
        // this.scene.add(new THREE.AmbientLight(0x5C5C5C));

        this.scene.add(this.camera);
    },
    //渲染器render初始化:
    initRenderer() {
        this.renderer = new THREE.WebGLRenderer({ 
            antialias: true,//开启反锯齿 
            // alpha: true //设置背景色透明
        });
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.setSize(window.innerWidth, 1080); //宽高可根据实际项目要求更改 如果是窗口高度改为innerHeight

        this.container = document.getElementById("container");
        this.container.appendChild(this.renderer.domElement);
        },
        initControl() {
        // 鼠标控制
        this.controls = new OrbitControls(this.camera, this.renderer.domElement);
        this.controls.target = new THREE.Vector3(0, 0, 0);
        // 视角最小距离
        this.controls.minDistance = 12;
        // 视角最远距离
        this.controls.maxDistance = 100;
        // 最大角度
        this.controls.maxPolarAngle = Math.PI/4;
    },
    //渲染:
    animate() {
        this.renderer.render(this.scene, this.camera);
        this.requestId = requestAnimationFrame(this.animate);
    },
    init() {
        this.initScene();
        this.initCamera();
        this.initRenderer();
        this.initControl();
    },
    onProgress(xhr) {
        if (xhr.lengthComputable) {
            var percentComplete = xhr.loaded / xhr.total * 100;
            console.log(Math.round(percentComplete, 2) + '% downloaded');
        }
    },
    /**加载模型 */
    loadPlant() {
        let that = this;
        var a = new Date().getTime() / 1000
        var gltfloader = new GLTFLoader()
        gltfloader.setDRACOLoader(new DRACOLoader());
        // gltfloader.load('../../static/UXSINO_CD/UXSINO_CD.gltf', function(gltf) {
        gltfloader.load('/static/UXSINO_CD/UXSINO_CD.gltf', function(gltf) {
            var object = gltf.scene
            var objBbox = new THREE.Box3().setFromObject(gltf.scene);
            var bboxCenter = objBbox.getCenter().clone();
            bboxCenter.multiplyScalar(-1);
            object.traverse(function(child) { //转换成threejs对象
                if (child instanceof THREE.Mesh) {
                    child.geometry.translate(bboxCenter.x, bboxCenter.y, bboxCenter.z);
                }
            });
            objBbox.setFromObject(object); // Update the bounding box
            var obj = object
            object.rotation.set(5, 0, 3)
            obj.scale.set(0.5, 0.5, 0.5)
            that.scene.add(obj);

            // var mesh = gltf.scene.children[0];
            // mesh.scale.set(10, 10, 10);
            // that.scene.add(mesh); // 将模型引入three

            // that.scene.add(object);
            // self.postMessage(JSON.stringify(scene.toJSON()))
            console.log(that.scene)
            console.log('webwork send scene')
            console.log((new Date().getTime() / 1000) - a + " s")
        }, this.onProgress);
    },
    loadPlant2() {
      let that = this;
      let objLoader = new OBJLoader();//obj模型加载器
      let mtlLoader = new MTLLoader();//材质文件加载器
      mtlLoader.load("/static/UXSINO_CD/UXSINO_CD.mtl", function(materials) {
        // materials.preload();
        objLoader.setMaterials(materials);//obj模型会和MaterialCreator包含的材质对应起来
        objLoader.load(
          "/static/UXSINO_CD/UXSINO_CD.obj",
          function(obj) {
            obj.position.set(0, 0, 0);//模型摆放的位置
            obj.scale.set(0.01, 0.01, 0.01);//模型放大或缩小的系数
            that.scene.add(obj);//将模型加入场景中
          },
          // called while loading is progressing
          function(xhr) {
            console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
          },
          // called when loading has errors
          function(error) {
            console.log("An error happened");
          }
        );
      });
    },
    onResize() {
      this.camera.aspect = window.innerWidth;  //宽高可根据实际项目要求更改 如果是窗口高度改为innerHeight
      this.camera.updateProjectionMatrix();
      this.renderer.setSize(window.innerWidth, window.innerWidth);  //宽高可根据实际项目要求更改 如果是窗口高度改为innerHeight
      // this.camera.aspect = window.innerWidth / 1080;  //宽高可根据实际项目要求更改 如果是窗口高度改为innerHeight
      // this.camera.updateProjectionMatrix();
      // this.renderer.setSize(window.innerWidth, 1080);  //宽高可根据实际项目要求更改 如果是窗口高度改为innerHeight
    }
  },
  mounted() {
    this.init();
    this.loadPlant();
    // this.loadPlant2();
    this.animate();
    document.getElementsByTagName("canvas")[0].style.verticalAlign = "bottom"; //解决canvas底部留白问题
    window.addEventListener("resize", this.onResize, false);
  },
  destroyed() {
    cancelAnimationFrame(this.requestId);
    this.scene = null;
    this.camera = null;
    this.renderer = null;
    this.controls = null;
    window.removeEventListener("resize", this.onResize, false);
  }
};
</script>

<style scoped>
#container {
  height: 1080px;
}
</style>